// pages/editUser/index.js
import api from '../../api/api'
import { areaList } from '../../utils/address';
import { isCodeCar,isPhone } from '../../utils/regular'
import { getYMDHMS } from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    form:{
      id: '',
      name: '',
      phone: '',
      addressInfo: '',
      code: '',
      medicalHistory: '',
      age: '',
      ageName: '',
      sex: '',
      height: '',
      weight: '',
      address: '',
      addressValue:''
    },
    currentDate: new Date().getTime(),
    minDate: new Date(1971,0,1).getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    showAge: false,
    showSex: false,
    showAddress: false,
    showHeight: false,
    showWeight: false,
    sexList:['男','女'],
    addressList:[],
    heightList: [],
    weightList: [],
    userInfo: {}
  },

  // 姓名输入
  inputName(e){
    this.setData({['form.name']: e.detail.value})
  },
  // 手机号输入
  inputPhone(e){
    console.log(e);
    this.setData({['form.phone']: e.detail.value})
  },
  // 身份证号码输入
  inputCode(e){
    this.setData({['form.code']: e.detail.value})
  },
  // 既往病史输入
  inputMedicalHistory(e){
    console.log(e);
    this.setData({['form.medicalHistory']: e.detail.value})
  },
  // 详细地址输入
  inputAddressInfo(e){
    console.log(e);
    this.setData({['form.addressInfo']: e.detail.value})
  },

  // 年龄弹窗及确定取消(出生日期时间戳)
  openAge(){
    this.setData({showAge: true})
  },
  onCancelAge(){
    this.setData({showAge: false})
  },
  onConfirmAge(e){
    let age = parseInt(e.detail.toString().slice(0,-3))
    this.setData({['form.age']: age})
    this.setData({['form.ageName']: getYMDHMS(age * 1000)})
    this.onCancelAge()
  },
  // 性别弹窗及确定取消
  openSex(){
    this.setData({showSex: true})
  },
  onCancelSex(){
    this.setData({showSex: false})
  },
  onConfirmSex(e){
    this.setData({['form.sex']: e.detail.value})
    this.onCancelSex()
  },
  // 地址弹窗及确定取消
  openAddress(){
    this.setData({showAddress: true})
  },
  onCancelAddress(){
    this.setData({showAddress: false})
  },
  onConfirmAddress(e){
    console.log(e);
    if(e.detail.values[0]!== undefined && e.detail.values[0].code && e.detail.values[1]!== undefined && e.detail.values[1].code && e.detail.values[2]!== undefined && e.detail.values[2].code){
      
      this.setData({['form.address']: e.detail.values[0].name + e.detail.values[1].name + e.detail.values[2].name})
      this.setData({['form.addressValue']: e.detail.values[0].code +','+ e.detail.values[1].code +','+ e.detail.values[2].code})
      this.onCancelAddress()
    }else{
      wx.showToast({
        title: '请选择到区',
        icon: 'none'
      })
    }
  },
  // 身高弹窗及确定取消
  openHeight(){
    this.setData({showHeight: true})
  },
  onCancelHeight(){
    this.setData({showHeight: false})
  },
  onConfirmHeight(e){
    this.setData({['form.height']: e.detail.value})
    this.onCancelHeight()
  },
  // 体重弹窗及确定取消
  openWeight(){
    this.setData({showWeight: true})
  },
  onCancelWeight(){
    this.setData({showWeight: false})
  },
  onConfirmWeight(e){
    this.setData({['form.weight']: e.detail.value})
    this.onCancelWeight()
  },
  // 提交信息
  saveUser(){
    // 校验表单
    if(!this.data.form.name){
      wx.showToast({
        title: '请填写姓名',
        icon: 'none'
      })
      return
    }
    if(!this.data.form.phone){
      wx.showToast({
        title: '请填写手机号',
        icon: 'none'
      })
      return
    }
    if(!this.data.form.age){
      wx.showToast({
        title: '请填写出生日期',
        icon: 'none'
      })
      return
    }
    if(!this.data.form.sex){
      wx.showToast({
        title: '请填写性别',
        icon: 'none'
      })
      return
    }
    if(!this.data.form.addressValue){
      wx.showToast({
        title: '请填写地址',
        icon: 'none'
      })
      return
    }
    if(!this.data.form.height){
      wx.showToast({
        title: '请填写身高',
        icon: 'none'
      })
      return
    }
    if(!this.data.form.weight){
      wx.showToast({
        title: '请填写体重',
        icon: 'none'
      })
      return
    }
    if(!this.data.form.code){
      wx.showToast({
        title: '请填写身份证号',
        icon: 'none'
      })
      return
    }
    if(!this.data.form.addressInfo){
      wx.showToast({
        title: '请填写详细地址',
        icon: 'none'
      })
      return
    }
    if(!isCodeCar(this.data.form.code).isCarId){
      wx.showToast({
        title: isCodeCar(this.data.form.code).message,
        icon: 'none'
      })
      return
    }
    if(!isPhone(this.data.form.phone)){
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      })
      return
    }
    let data = {
      id: this.data.form.id,
      name: this.data.form.name,
      tel: this.data.form.phone,
      addressInfo: this.data.form.addressInfo,
      code: this.data.form.code,
      medical_history: this.data.form.medicalHistory,

      age: this.data.form.age,
      sex: this.data.form.sex === '男' ? 1 : 2,
      height: this.data.form.height,
      weight: this.data.form.weight,
      addressValue: this.data.form.addressValue
    }
    // 保存表单
    api.saveUser(data).then(res => {
      if(res.data.code === 200){
        wx.navigateBack({
          delta: 1
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let listHeight = [];
    let listWeight = [];
    for(let i = 1;i <= 300;i++){
      listHeight.push(i);
    }
    for(let i = 1;i <= 150;i++){
      listWeight.push(i);
    }
    this.setData({heightList: listHeight,weightList: listWeight});
    this.setData({addressList: areaList});
    api.getUserInfo().then(res => {
      if(res.data.code === 200){
        this.setData({userInfo: res.data.data});
        this.setData(
          {
            ['form.id']: this.data.userInfo.id,
            ['form.name']: this.data.userInfo.name,
            ['form.phone']: this.data.userInfo.tel,
            ['form.code']: this.data.userInfo.code,
            ['form.medicalHistory']: this.data.userInfo.medical_history,
            ['form.age']: this.data.userInfo.age,
            ['form.addressValue']: this.data.userInfo.province.toString()+','+this.data.userInfo.city.toString()+','+this.data.userInfo.area.toString(),
            ['form.addressInfo']: this.data.userInfo.address,
            ['form.sex']: this.data.userInfo.sex === 1 ? '男' : '女',
            ['form.ageName']: getYMDHMS(this.data.userInfo.age * 1000),
            ['form.height']: this.data.userInfo.high,
            ['form.weight']: this.data.userInfo.weight,
          }
        )
        // 年龄picker回显
        this.setData({currentDate: this.data.userInfo.age * 1000})
        // 性别picker回显
        const sexPicker = this.selectComponent('.sex_picker')
        sexPicker.setValues([this.data.userInfo.sex === 1 ? '男' : '女'])
        // 地址picker回显
        let str = areaList.province_list[this.data.userInfo.province.toString()] + areaList.city_list[this.data.userInfo.city.toString()] + areaList.county_list[this.data.userInfo.area.toString()];
        this.setData({['form.address']: str})
        const addressPicker = this.selectComponent('.address_picker')
        addressPicker.reset(this.data.userInfo.area.toString())
        // 身高picker回显
        const heightPicker = this.selectComponent('.height_picker')
        heightPicker.setValues([this.data.userInfo.high])
        // 体重picker回显
        const weightPicker = this.selectComponent('.weight_picker')
        weightPicker.setValues([this.data.userInfo.weight])
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})